﻿/*
=======================================================
    BillDetail【单据明细】
=======================================================
*/

using Microsoft.AspNetCore.Mvc.Formatters;

namespace Services
{
    public interface IBillDetailLogic : ILogic<BillDetailModel, BillDetailFilterModel>
    {
    }


    public class BillDetailLogic : BaseLogic<BillDetailModel, BillDetailFilterModel, BillDetail, IBillDetailRepository, IBillDetailMapping, IBillDetailService>, IBillDetailLogic
    {
        private readonly IBillRepository _IBillRepository;
        private readonly IBillMapping _IBillMapping;
        public BillDetailLogic(ICurrentUser currentUser, IBillDetailRepository repository, IBillDetailMapping mapping, IBillDetailService service, IBillRepository iBillRepository, IBillMapping iBillMapping)
            : base(currentUser, repository, mapping, service)
        {
            _IBillRepository = iBillRepository;
            _IBillMapping = iBillMapping;
        }

        #region GetPage
        public override PageModel<BillDetailModel> GetPage(BillDetailFilterModel filterModel, int pageIndex = 1, int pageSize = 20, string orderBy = null)
        {
            PageModel<BillDetailModel> pageModel = new PageModel<BillDetailModel>();

            var (items, totalCount) = _repository.GetPage(_mapping.FilterModel2Where(filterModel), pageIndex, pageSize, orderBy);
            pageModel.TotalCount = totalCount;
            var ItemsTemp = _mapping.Entity2Model(items);

            var ids = ItemsTemp.Select(x => x.BillID).ToList();

            var where = Expressionable.Create<Bill>();
            where = where.And(x => ids.Contains(x.BillID));
            var list = _IBillMapping.Entity2Model(_IBillRepository.GetSearch(where));

            foreach (var item in ItemsTemp)
            {
                item.BillModel = list.FirstOrDefault(x => x.BillID == item.BillID);
            }

            pageModel.Items = ItemsTemp;

            return pageModel;
        } 
        #endregion
    }
}
